package com.liaobowen.servlet;

import com.liaobowen.bean.User;
import com.liaobowen.service.UserService;
import com.liaobowen.service.impl.UserServiceImpl;
import com.liaobowen.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 本项目采用的是myBatist框架 ，使用的是《xml配置文件》的方式实现 增删改查
 */
@WebServlet(value = "/page/UserServlet")
public class UserServlet extends HttpServlet {

    private UserService userService;

    public UserServlet() {
        userService = new UserServiceImpl();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码格式
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        //判断执行那些操作
        String method = request.getParameter("method");
        if ("add".equals(method)) {
            //添加
        } else if ("delete".equals(method)) {
            //删除
        } else {

            //接受查询条件
            String name = request.getParameter("name");
            String aegMin = request.getParameter("aegMin");
            String ageMax = request.getParameter("ageMax");
//            封装查询条件
            User user = new User();
            if (StringUtil.isNotEmpty(name)) {
                user.setName(name);
            }
            user.setAge(StringUtil.parseStringToInt(aegMin));
            user.setMaxAge(StringUtil.parseStringToInt(ageMax));


            //查询列表
            List userList = userService.getUserList(user);
            //将集合存储到request作用域中
            request.setAttribute("userList", userList);
            request.setAttribute("queryUser", user);
            //
            request.getRequestDispatcher("/page/user/index.jsp").forward(request, response);
        }


    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
